package org.example.mall.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传工具类
 */
@Slf4j
@Component
public class FileUploadUtil {
    
    private static String uploadPath;
    private static List<String> allowedTypes;
    private static long maxSize;
    
    @Value("${file.upload.path:./uploads/images/}")
    public void setUploadPath(String path) {
        FileUploadUtil.uploadPath = path;
        // 确保目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            boolean created = uploadDir.mkdirs();
            if (created) {
                log.info("Created upload directory: {}", uploadPath);
            } else {
                log.warn("Failed to create upload directory: {}", uploadPath);
            }
        }
        
        // 输出上传目录的绝对路径，方便调试
        log.info("Upload directory absolute path: {}", uploadDir.getAbsolutePath());
    }
    
    @Value("${file.upload.allowed-types:image/jpeg,image/png,image/gif}")
    public void setAllowedTypes(String types) {
        FileUploadUtil.allowedTypes = Arrays.asList(types.split(","));
    }
    
    @Value("${file.upload.max-size:5242880}")
    public void setMaxSize(long maxSize) {
        FileUploadUtil.maxSize = maxSize;
    }
    
    /**
     * 保存上传的文件
     * @param file 上传的文件
     * @return 文件相对路径
     * @throws IOException 文件保存异常
     * @throws IllegalArgumentException 文件类型/大小验证失败
     */
    public static String saveFile(MultipartFile file) throws IOException, IllegalArgumentException {
        if (file == null || file.isEmpty()) {
            return null;
        }
        
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !allowedTypes.contains(contentType)) {
            throw new IllegalArgumentException("不支持的文件类型");
        }
        
        // 验证文件大小
        if (file.getSize() > maxSize) {
            throw new IllegalArgumentException("文件大小超出限制");
        }
        
        // 生成唯一的文件名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        Path filePath = Paths.get(uploadPath + fileName);
        Files.copy(file.getInputStream(), filePath);
        log.info("Saved file: {}", filePath.toAbsolutePath());
        
        // 返回相对路径 (用于在JSP等前端页面中访问)
        String relativePath = "/uploads/images/" + fileName;
        log.info("File relative path: {}", relativePath);
        return relativePath;
    }
}